package com.qiaofang.service.impl;

import com.google.common.collect.Lists;
import com.qiaofang.common.constant.CommonResponseCode;
import com.qiaofang.common.constant.DelFlagEnum;
import com.qiaofang.common.constant.ExceptionEnum;
import com.qiaofang.common.exception.BusinessException;
import com.qiaofang.common.model.PageDTO;
import com.qiaofang.common.model.UiListBean;
import com.qiaofang.common.response.CommonResponse;
import com.qiaofang.common.response.SuccessfulResponseFactory;
import com.qiaofang.common.utils.StringUtil;
import com.qiaofang.constant.MechanismStatusEnum;
import com.qiaofang.dto.AdviserDTO;
import com.qiaofang.dto.PremisesDTO;
import com.qiaofang.entity.EstateAdviser;
import com.qiaofang.entity.Premises;
import com.qiaofang.entity.PremisesRelation;
import com.qiaofang.entity.enums.*;
import com.qiaofang.mapper.PremisesMapper;
import com.qiaofang.repository.PremisesRelationRepository;
import com.qiaofang.repository.PremisesRepository;
import com.qiaofang.service.PremisesService;
import com.qiaofang.vo.PremisesVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class PremisesServiceImpl implements PremisesService {

    private static final Logger logger = LoggerFactory.getLogger(PremisesServiceImpl.class);

    @Autowired
    private PremisesMapper premisesMapper;

    @Autowired
    private PremisesRepository premisesRepository;

    @Autowired
    private PremisesRelationRepository premisesRelationRepository;

    @Override
    public void addPremisesRelation(Long merchantCompanyId, Long distributionCompanyId) {
        Premises example = new Premises();
        example.setDelFlag(DelFlagEnum.UNDEL.getNo());
        example.setCompanyId(merchantCompanyId);
        List<Premises> list = premisesMapper.selectIdListByCompanyId(merchantCompanyId);
        if (list != null) {
            List<PremisesRelation> premisesRelations = Lists.newArrayList();
            for (Premises premises : list) {
                PremisesRelation premisesRelation = new PremisesRelation();
                premisesRelation.setDevCompanyId(merchantCompanyId);
                premisesRelation.setAgentCompanyId(distributionCompanyId);
                premisesRelation.setPremisesId(premises.getId());
                premisesRelation.setDelFlag(DelFlagEnum.UNDEL.getNo());
                premisesRelation.setStatus(MechanismStatusEnum.Enable.getNo());
                premisesRelations.add(premisesRelation);
            }
            premisesRelationRepository.saveAll(premisesRelations);
        }
    }

    @Override
    public List<Premises> listPremisesByName(Set<String> premisesNameList, Long companyId) {
        return premisesRepository.listPremisesByName(premisesNameList, companyId);
    }

    @Override
    public UiListBean listPremises(PremisesDTO dto, PageDTO page) {
        UiListBean<PremisesVO> uiListBean = new UiListBean();
        PremisesDTO premisesDTO = new PremisesDTO();
        premisesDTO.setCompanyName(dto.getCompanyName());
        premisesDTO.setName(dto.getName());
        List<Premises> premisesList = premisesMapper.listPremises(premisesDTO, page);
        List<PremisesVO> voList = new ArrayList<>();
        if(null == premisesList || premisesList.size() == 0){
            return uiListBean;
        }
        for(Premises premises: premisesList){
            PremisesVO vo = new PremisesVO();
            BeanUtils.copyProperties(premises, vo);
            if(StringUtils.isNotBlank(vo.getPremisesStatus())){
                vo.setPremisesStatus(PremisesStatusEnum.getByNo(vo.getPremisesStatus()).getDes());
            }
            if(StringUtils.isNotBlank(vo.getSaleStatus())){
                vo.setSaleStatus(SaleStatusEnum.getByNo(vo.getSaleStatus()).getDes());
            }

            if(StringUtils.isNotBlank(vo.getReportWay())){
                vo.setReportWay(ReportWayEnum.getByNo(vo.getReportWay()).getDes());
            }else{
                vo.setReportWay("不限");
            }

            if(StringUtils.isNotBlank(vo.getRepeatReportFlag())){
                vo.setRepeatReportFlag(SwitchEnum.getByNo(vo.getRepeatReportFlag()).getDes());
            }else{
                vo.setRepeatReportFlag("关闭");
            }
            if(StringUtils.isNotBlank(vo.getVisitProtectSwitch())){
                vo.setVisitProtectSwitch(SwitchEnum.getByNo(vo.getVisitProtectSwitch()).getDes());
            }else{
                vo.setVisitProtectSwitch("关闭");
            }
            if(StringUtils.isNotBlank(vo.getRepeatDelayDealTime())){
                vo.setRepeatDelayDealTime(SwitchEnum.getByNo(vo.getRepeatDelayDealTime()).getDes());
            }else{
                vo.setRepeatDelayDealTime("关闭");
            }

            if(StringUtils.isNotBlank(vo.getReportProtectType())){
                if(!TimeUnitTypeEnum.NONE.getNo().equals(vo.getReportProtectType())){
                    vo.setReportProtect(calTimeByUnit(vo.getReportProtectType(), vo.getReportProtect()));
                }else{
                    vo.setReportProtect("");
                }
                vo.setReportProtectType(TimeUnitTypeEnum.getDescByNo(vo.getReportProtectType()));
            }else{
                vo.setReportProtectType("未设置");
                vo.setReportProtect("");
            }

            if(StringUtils.isNotBlank(vo.getSpecialTimeType())){
                if(!TimeUnitTypeEnum.NONE.getNo().equals(vo.getSpecialTimeType())){
                    vo.setSpecialTime(calTimeByUnit(vo.getSpecialTimeType(), vo.getSpecialTime()));
                }else{
                    vo.setSpecialTime("");
                }
                vo.setSpecialTimeType(TimeUnitTypeEnum.getDescByNo(vo.getSpecialTimeType()));
            }else{
                vo.setSpecialTimeType("未设置");
                vo.setSpecialTime("");
            }

            if(StringUtils.isNotBlank(vo.getVisitProtectType())){
                if(!TimeUnitTypeEnum.NONE.getNo().equals(vo.getVisitProtectType())){
                    vo.setVisitProtect(calTimeByUnit(vo.getVisitProtectType(), vo.getVisitProtect()));
                }else{
                    vo.setVisitProtect("");
                }
                vo.setVisitProtectType(TimeUnitTypeEnum.getDescByNo(vo.getVisitProtectType()));
            }else{
                vo.setVisitProtectType("未设置");
                vo.setVisitProtect("");
            }

            if(StringUtils.isNotBlank(vo.getSaveDaysType())){
                if(!TimeUnitTypeEnum.NONE.getNo().equals(vo.getSaveDaysType())){
                    vo.setSaveDays(calTimeByUnit(vo.getSaveDaysType(), vo.getSaveDays()));
                }else{
                    vo.setSaveDays("");
                }
                vo.setSaveDaysType(TimeUnitTypeEnum.getDescByNo(vo.getSaveDaysType()));
            }else{
                vo.setSaveDaysType("未设置");
                vo.setSaveDays("");
            }
            voList.add(vo);
        }
        uiListBean.setList(voList);
        uiListBean.setTotalCount(premisesMapper.listPremisesCount(premisesDTO));
        return uiListBean;
    }

    private static String calTimeByUnit(String unit, String min){
        int result = Integer.parseInt(min==null?"0":min);
        if(TimeUnitTypeEnum.HOUR.getNo().equals(unit)){
            result = Integer.parseInt(min) / 60;
        }else if(TimeUnitTypeEnum.DAY.getNo().equals(unit)){
            result = Integer.parseInt(min) / 60 / 24;
        }
        return String.valueOf(result);
    }


    @Override
    public List<Premises> getListPremisesByExample(Example example) {
        return premisesMapper.selectByExample(example);
    }

    @Override
    public void deletePremises(Long id) {
        Premises premises=premisesRepository.findById(id)
                .orElseThrow(()->new BusinessException(ExceptionEnum.NOT_FIND_DB_DATA));
        premises.setDelFlag(DelFlagEnum.DEL.getNo());
        premisesRepository.save(premises);
    }

    @Override
    public CommonResponse refreshAdviser(Long premisesId) {
        CommonResponse response = new CommonResponse();

        if ( null == premisesId ){
            response.setResponseCode(CommonResponseCode.RC_PARAMETER_ERROR.getResponseCode());
            response.setResponseMessage(CommonResponseCode.RC_PARAMETER_ERROR.getResponseMessage());
            return response;
        }
        /**
         * 查询目前该楼盘绑定的 置业顾问
         */
        AdviserDTO adviserDTO = new AdviserDTO();
        adviserDTO.setPremisesId(premisesId);
        adviserDTO.setDeleted(DelFlagEnum.UNDEL.getNo());
        List<EstateAdviser> estateAdviserList = premisesMapper.listAdviser(adviserDTO);

        if (CollectionUtils.isEmpty(estateAdviserList)) {
            response.setResponseCode("0");
            response.setResponseMessage("该楼盘没有置业顾问！");
            return response;
        }
        for (EstateAdviser estateAdviser : estateAdviserList){
            /**
             * 查询该置业顾问 曾经绑定该楼盘
             */
            if (null == estateAdviser.getPartnerId()){
                continue;
            }
            adviserDTO.setDeleted(DelFlagEnum.DEL.getNo());
            adviserDTO.setPremisesId(estateAdviser.getPremisesId());
            adviserDTO.setPartnerId(estateAdviser.getPartnerId());
            List<EstateAdviser> estateAdvisers = premisesMapper.listAdviser(adviserDTO);

            if (CollectionUtils.isEmpty(estateAdvisers)){
                continue;
            }
            List<String> adviserUuidList = estateAdvisers.stream().map(EstateAdviser::getAdviserUuid).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(adviserUuidList)){
                premisesMapper.refreshAdviser(estateAdviser.getAdviserUuid(),adviserUuidList);
            }
        }

        response = SuccessfulResponseFactory.getSuccessResponse();
        return response;
    }

    @Override
    public CommonResponse refreshAdviserByPartnerId(Long partnerId) {
        CommonResponse response = new CommonResponse();

        if ( null == partnerId ){
            response.setResponseCode(CommonResponseCode.RC_PARAMETER_ERROR.getResponseCode());
            response.setResponseMessage(CommonResponseCode.RC_PARAMETER_ERROR.getResponseMessage());
            logger.info("接口:refreshAdviserByPartnerId -> 入参 partnerId = null");
            return response;
        }
        /**
         * 查询该人员的所有 置业顾问关系
         */
        AdviserDTO adviserDTO = new AdviserDTO();
        adviserDTO.setPartnerId(partnerId);
        adviserDTO.setDeleted(DelFlagEnum.UNDEL.getNo());
        List<EstateAdviser> estateAdviserList = premisesMapper.listAdviser(adviserDTO);

        if (CollectionUtils.isEmpty(estateAdviserList)) {
            response.setResponseCode("0");
            response.setResponseMessage("该人员不是任何楼盘的置业顾问！");
            logger.info("人员 partnerId：{} 不是任何楼盘的置业顾问",partnerId);
            return response;
        }
        logger.info("人员 partnerId：{} 目前存在的置业顾问关系:{}",partnerId,estateAdviserList);
        for (EstateAdviser estateAdviser : estateAdviserList){
            /**
             * 查询该置业顾问 曾经绑定过相同楼盘的 关系
             */
            if (null == estateAdviser.getPremisesId()){
                continue;
            }
            adviserDTO.setDeleted(DelFlagEnum.DEL.getNo());
            adviserDTO.setPremisesId(estateAdviser.getPremisesId());
            adviserDTO.setPartnerId(estateAdviser.getPartnerId());
            List<EstateAdviser> estateAdvisers = premisesMapper.listAdviser(adviserDTO);

            if (CollectionUtils.isEmpty(estateAdvisers)){
                continue;
            }
            List<String> adviserUuidList = estateAdvisers.stream().map(EstateAdviser::getAdviserUuid).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(adviserUuidList)){
                premisesMapper.refreshAdviser(estateAdviser.getAdviserUuid(),adviserUuidList);
            }
        }

        response = SuccessfulResponseFactory.getSuccessResponse();
        return response;
    }


}
